<?php

namespace App\Http\Middleware;

use Closure;
use Route;

class CheckRbac
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $current_user = auth('admin')->user();
        // //注意例外用户
        if ($current_user->role_id == 1) {
            return $next($request);
        }
        $alert_pwd_msg = check_chage_pwd(); //验证密码是否n+个月没改过
        if ($alert_pwd_msg) {
            echo "<script>parent.location.href=document.referrer;</script>";
            die;
        }
        /*************验证其他设备是否登录+退出 start**************/
            if ($current_user->remember_token != csrf_token()) {
                //删除用户信息
                auth('admin')->logout();
                return redirect(route('loginAdmin'));
            }
        /*************验证其他设备是否登录+退出 end**************/
        
        //RBAC鉴权
        //获取当前访问的路由
        $current_route = Route::current()->uri;
        //获取当前用户对应的角色已经具备的权限，注意例外
        $current_role = $current_user->role;
        $arr_have_routes = [];
        if ($current_role) {
            //如果有对应的角色
            $str_auth_ids = $current_role->auth_ids;
            $arr_auth_ids = explode(',', $str_auth_ids);//字符串 --》数组 
            $tmp = \App\Admin\Auth::where('url', '<>', '')->whereIn('id', $arr_auth_ids)->pluck('url');
            $arr_have_routes = $tmp->toArray();
        }
        //添加两个  是人就有的权限
        // $arr_have_routes[]= 'admin/index/index';
        // $arr_have_routes[]= 'admin/index/welcome';
        $b = in_array($current_route, $arr_have_routes);

        if (!$b) {
            if ($request->expectsJson()) {
                // return response()->json(['message' => "无权操作"], 403);
                return abort(403);;
            } else {
                echo view('admin.public.withoutAuth');
            }
            exit;
        }
                //继续后续的请求
        return $next($request);
    }
}
